var icd = require('../models/icd.js');
var ccd = require('../models/ccd.js');
var icdIndex = require('../models/icdIndex.js');
var ccdIndex = require('../models/ccdIndex.js');
var ObjectID = require("mongodb").ObjectID;

exports.on = function(req,res) {
    var filter = {};
    filter["_id"] = ObjectID(req.params.id);
    console.log(filter);

    ccd.get(filter,function(err,doc){
        console.log("+++++++");
        console.log(doc);
        res.render('user-involve', {
            title: '参与项目',
            user : req.session.user,
            ccd  : doc,
            success : "",
            error : ""
        });
    });
};

exports.create = function(req,res){
    var filter = {};
    filter["user"] = req.params.user;
    icdIndex.get(filter,function(err,doc){
        if(doc[0] === undefined)  icdIndex.create(filter,function(err,doc){
            return res.redirect(req.url);
        });
        else if(doc[0][ObjectID(req.params.id)] != undefined)
            return res.redirect('/'+req.params.user+'/involved/'+doc[0][ObjectID(req.params.id)]["ccd_id"]);

        //else
        var filter = {};
        filter["ccd_id"] =ObjectID(req.params.id);

        ccdIndex.get(filter,function(err,doc){
            var filter = {};
            var ccd_index = doc[0];
            filter["user"] = req.params.user;
            filter["ccd_id"] = ObjectID(req.params.id);
            filter["cd"] = ccd_index["cd"];
            filter["class"] = {};
            filter["relation"] = {};
            icd.create(filter,function(err){
                console.log(err);
                console.log(doc);
                res.redirect('/'+req.params.user+'/involved/'+req.params.id);
            });

        });

    });
}